package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ContractType;
import com.ruoyi.system.mapper.ContractTypeMapper;
import com.ruoyi.system.service.IContractTypeService;

/**
 * 合同类型Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class ContractTypeServiceImpl implements IContractTypeService 
{
    @Autowired
    private ContractTypeMapper contractTypeMapper;

    /**
     * 查询合同类型
     * 
     * @param typeId 合同类型主键
     * @return 合同类型
     */
    @Override
    public ContractType selectContractTypeByTypeId(Long typeId)
    {
        return contractTypeMapper.selectContractTypeByTypeId(typeId);
    }

    /**
     * 查询合同类型列表
     * 
     * @param contractType 合同类型
     * @return 合同类型
     */
    @Override
    public List<ContractType> selectContractTypeList(ContractType contractType)
    {
        return contractTypeMapper.selectContractTypeList(contractType);
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param contractTypes 合同类型列表
     * @return 树结构列表
     */
    @Override
    public List<ContractType> buildContractTypeTree(List<ContractType> contractTypes)
    {
        List<ContractType> returnList = new ArrayList<ContractType>();
        List<Long> tempList = new ArrayList<Long>();
        for (ContractType contractType : contractTypes)
        {
            tempList.add(contractType.getTypeId());
        }
        for (Iterator<ContractType> iterator = contractTypes.iterator(); iterator.hasNext();)
        {
            ContractType contractType = (ContractType) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(contractType.getParentId()))
            {
                recursionFn(contractTypes, contractType);
                returnList.add(contractType);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = contractTypes;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ContractType> list, ContractType t)
    {
        // 得到子节点列表
        List<ContractType> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ContractType tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ContractType> getChildList(List<ContractType> list, ContractType t)
    {
        List<ContractType> tlist = new ArrayList<ContractType>();
        Iterator<ContractType> it = list.iterator();
        while (it.hasNext())
        {
            ContractType n = (ContractType) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getTypeId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ContractType> list, ContractType t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 新增合同类型
     * 
     * @param contractType 合同类型
     * @return 结果
     */
    @Override
    public int insertContractType(ContractType contractType)
    {
        ContractType info = contractTypeMapper.selectContractTypeByTypeId(contractType.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (StringUtils.isNotNull(info) && !ContractType.NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("合同类型停用，不允许新增");
        }
        contractType.setCreateTime(DateUtils.getNowDate());
        return contractTypeMapper.insertContractType(contractType);
    }

    /**
     * 修改合同类型
     * 
     * @param contractType 合同类型
     * @return 结果
     */
    @Override
    public int updateContractType(ContractType contractType)
    {
        ContractType newParentContractType = contractTypeMapper.selectContractTypeByTypeId(contractType.getParentId());
        ContractType oldContractType = contractTypeMapper.selectContractTypeByTypeId(contractType.getTypeId());
        if (StringUtils.isNotNull(newParentContractType) && StringUtils.isNotNull(oldContractType))
        {
            String newAncestors = newParentContractType.getAncestors() + "," + newParentContractType.getTypeId();
            String oldAncestors = oldContractType.getAncestors();
            contractType.setAncestors(newAncestors);
            updateContractTypeChildren(contractType.getTypeId(), newAncestors, oldAncestors);
        }
        contractType.setUpdateTime(DateUtils.getNowDate());
        return contractTypeMapper.updateContractType(contractType);
    }

    /**
     * 修改子元素关系
     * 
     * @param typeId 被修改的合同类型ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateContractTypeChildren(Long typeId, String newAncestors, String oldAncestors)
    {
        List<ContractType> children = contractTypeMapper.selectChildrenContractTypeById(typeId);
        for (ContractType child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            contractTypeMapper.updateContractTypeChildren(children);
        }
    }

    /**
     * 删除合同类型信息
     * 
     * @param typeId 合同类型主键
     * @return 结果
     */
    @Override
    public int deleteContractTypeByTypeId(Long typeId)
    {
        return contractTypeMapper.deleteContractTypeByTypeId(typeId);
    }

    /**
     * 校验合同类型名称是否唯一
     * 
     * @param contractType 合同类型信息
     * @return 结果
     */
    @Override
    public String checkContractTypeNameUnique(ContractType contractType)
    {
        Long typeId = StringUtils.isNull(contractType.getTypeId()) ? -1L : contractType.getTypeId();
        ContractType info = contractTypeMapper.checkContractTypeNameUnique(contractType.getTypeName(), contractType.getParentId());
        if (StringUtils.isNotNull(info) && info.getTypeId().longValue() != typeId.longValue())
        {
            return "1";
        }
        return "0";
    }

    /**
     * 是否存在合同类型子节点
     * 
     * @param typeId 合同类型ID
     * @return 结果
     */
    @Override
    public boolean hasChildByContractTypeId(Long typeId)
    {
        int result = contractTypeMapper.hasChildByContractTypeId(typeId);
        return result > 0;
    }

    /**
     * 查询合同类型是否存在合同
     * 
     * @param typeId 合同类型ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkContractTypeExistContract(Long typeId)
    {
        return false; // 需要根据实际业务实现，目前暂时返回false
    }

    /**
     * 查询合同类型正常状态的子节点数量
     *
     * @param typeId 部门ID
     * @return 子节点数量
     */
    @Override
    public int selectNormalChildrenContractTypeById(Long typeId)
    {
        return contractTypeMapper.selectNormalChildrenContractTypeById(typeId);
    }
}
